import {
	Button,
	Collapse,
	Form,
	Input,
	message,
	Tag,
	Popconfirm,
	Row,
	Col,
	Select,
	Upload,
	Tabs,
	TreeSelect,
	DatePicker,
} from 'antd'
import React, {memo, useState, useEffect, useRef} from 'react'
import {EditableProTable} from '@ant-design/pro-components'
import {history, connect} from 'umi'
import moment from 'moment'
import type {ColumnsType} from 'antd/es/table'
import type {
	ActionType,
	EditableFormInstance,
	ProColumns,
} from '@ant-design/pro-components'
import styles from './index.less'
import CustomTable from '@/components/Table'
import {getDict} from '@/service/common/dict'
import {getBusinessCode} from '@/service/purchase/common'
import {getCompany, processRecordSave} from '@/service/common/index'
import {getAllContractList} from '@/service/purchase/contract'
import {uploadMoreProps, getPublicDownloadUrl} from '@/service/common/upload'
import {getWriteTableList} from '@/service/purchase/payment'
import {getWarehouseinList} from '@/service/storage/inAtorage'
import {twoDecimalPattern} from '@/utils/common/validator'
import 'moment/locale/zh-cn'
import {
	addPlan,
	editPlan,
	viewPlan,
	copyPlan,
	getTableListDetail,
	planAuditFlow,
	planProcessAdd,
	planRelaunchFlow,
	planSaveTemporary,
} from '@/service/purchase/plan'
import {dictByCode} from '@/service/purchase/apply'
import {getDeptList} from '@/service/system/dept'
import {translateDataToTree, getEditTableSelect} from '@/utils/common/index'
import Examine from '@/components/Examine'
import {getIsProcessOpen} from '@/service/purchase/initiation'
import OperationRecord from '@/components/OperationRecord'

const {Panel} = Collapse
const {TextArea} = Input
type TreeItem = {
	id: string
	parentId: number
	name: string
	children?: Array<TreeItem>
}[]

type OtherParams = {
	requisitionName?: string
	requisitionOrgname?: string
	purchaserName?: string
	contractTypename?: string
	supplierName?: string
	supplierNo?: string
	startTime?: string
	finishTime?: string
	applicantId?: string
	payCityname?: string
	payDeptname?: string
	planId?: string
}

type DataSourceType = {
	id: React.Key
	labels?: {
		key: string
		label: string
	}[]
	state?: string
	children?: DataSourceType[]
}

const add = memo(
	(props: {
		global: {currentRoute: any}
		dispatch: any
		user: {userId: string; userName: string; orgId: string | number}
		location: any
	}) => {
		const {dispatch} = props
		const {currentRoute} = props.global
		const {query} = props.location
		const examineRef = useRef<any>(null)
		const [planId, setPlanId] = useState<any>()
		const [contractId, setContractId] = useState<string>()
		const [type, setType] = useState<any>()
		const [form] = Form.useForm()
		const [otherParams, setOtherParams] = useState<OtherParams>()
		const [requisitionTypeList, setRequisitionTypeList] = useState<any[]>(
			[],
		)
		const [dict, setDict] = useState({
			Car_Type: [],
			Service_Type: [],
			Physical_Type: [],
			IN_WAREHOUSE_STATUS: [],
			purchase_planitem_unit: [],
		})
		const [orgList, setOrgList] = useState<TreeItem>([])
		const [companyList, setCompanyList] = useState([])
		const actionRef = useRef<ActionType>()
		const editorFormRef = useRef<EditableFormInstance<DataSourceType>>()
		const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
		const [planitemList, setPlanitemList] = useState<
			readonly DataSourceType[]
		>([])
		const [fileList, setFileList] = useState<any>([])
		const [purchaseParams, setPurchaseParams] = useState({
			current: 1,
			size: 10,
		})
		const [purchaseTotal, setPurchaseTotal] = useState(0)
		const [purchaseLoading, setPurchaseLoading] = useState(false)
		const [purchaseList, setPurchaseList] = useState([])
		const [allContractList, setAllContractList] = useState([])
		const [sourceDocNo, setSourceDocNo] = useState()
		const [writeParams, setWriteParams] = useState({
			current: 1,
			size: 10,
		})
		const [writeList, setWriteList] = useState([])
		const [writeTotal, setWriteTotal] = useState(0)
		const [writeLoading, setWriteLoading] = useState(false)
		const [totalNum, setTotalNum] = useState('0')
		// 流程id
		const [instanceId, setInstanceId] = useState<string>()
		const [processOpen, setProcessOpen] = useState<number>(0)
		const [auditStatus, setAuditStatus] = useState<string>('0')
		const [newApplyTime, setNewApplyTime] = useState('')
		const goback = () => {
			const {goPath, pathParams} = props.location.query
			dispatch({
				type: 'global/deleteTabs',
				payload: currentRoute,
			})
			if (goPath) {
				if (pathParams) {
					history.push({
						pathname: goPath,
						query: {
							id: pathParams,
						},
					})
				} else {
					history.push({
						pathname: goPath,
					})
				}
			} else {
				history.push({
					pathname: '/purchase/plan',
				})
			}
		}

		// 初始化-流程是否激活
		const getIsProcessOpenFun = () => {
			getIsProcessOpen({businessType: 4})
				.then((res: any) => {
					if (res?.success) {
						setProcessOpen(res?.data)
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 初始化-确认收货列表
		const getPurchaseList = () => {
			setPurchaseLoading(() => true)
			getWarehouseinList({...purchaseParams, sourceDocNo})
				.then((res: any) => {
					if (res?.success) {
						setPurchaseList(() => res?.data?.records)
						setPurchaseTotal(() => res?.data?.total)
					}
					setPurchaseLoading(() => false)
				})
				.catch((err) => {
					setPurchaseLoading(() => false)
					message.error(err)
				})
		}
		useEffect(() => {
			if (type !== 'copy' && sourceDocNo) {
				getPurchaseList()
			}
		}, [writeParams, sourceDocNo])

		// 初始化-发票核销分页列表
		const onInvoiceListFun = () => {
			setWriteLoading(true)
			getWriteTableList({...writeParams, planId})
				.then((res: any) => {
					if (res?.data?.records) {
						setWriteList(() => res.data.records)
						setWriteTotal(res.data.total)
					}
					setWriteLoading(false)
				})
				.catch(() => {
					setWriteLoading(false)
				})
		}

		useEffect(() => {
			if (type !== 'copy' && planId) {
				onInvoiceListFun()
			}
		}, [writeParams, planId])

		// 初始化-采购计划申请单编号
		const onAllContractList = () => {
			getAllContractList({id: contractId})
				.then((res: any) => {
					if (res?.success) {
						setAllContractList(() => res?.data)
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		useEffect(() => {
			onAllContractList()
		}, [contractId])

		// 初始化-采购计划申请单编号
		const onCodeFun = () => {
			getBusinessCode({businessType: 4})
				.then((res: any) => {
					if (res?.success) {
						form.setFieldsValue({planNo: res?.data})
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 初始化-需求组织数据
		const getDeptFun = () => {
			getDeptList({merchantId: props.user.orgId}).then((res: any) => {
				if (res?.success) {
					const list = translateDataToTree(res.data)
					setOrgList(() => list as any)
				}
			})
		}

		// 初始化-采购类目
		const onDictByCodeFun = () => {
			dictByCode('purchase_requisition_type')
				.then((res: any) => {
					if (res?.success) {
						setRequisitionTypeList(() => res?.data)
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 获取公司数据
		const onAllCompany = () => {
			getCompany({merchantId: props.user.orgId}).then((res: any) => {
				if (res?.success) {
					const list = translateDataToTree(res?.data)
					setCompanyList(() => list as any)
				}
			})
		}

		useEffect(() => {
			getDeptFun()
			onAllCompany()
			onDictByCodeFun()
		}, [props.user.orgId])

		// 初始化-详情数据
		const getListDetail = (id: string) => {
			getTableListDetail({planId: id}).then((res: any) => {
				if (res?.success) {
					setPlanitemList(res?.data)
				}
			})
		}
		// 初始化-附件列表
		const getFileList = (ids: any) => {
			getPublicDownloadUrl(ids).then((res: any) => {
				if (res?.success) {
					const list = res?.data.map((item: any) => ({
						name: item?.filename,
						status: 'done',
						url: item?.url,
						response: {
							data: {
								id: item?.id,
							},
						},
					}))
					setFileList(() => [...list])
				}
			})
		}
		// 初始化-详情数据
		const getView = (id: any) => {
			viewPlan(id).then((res: any) => {
				if (res?.success) {
					setNewApplyTime(res?.data?.applyTime)
					delete res?.data?.applyTime
					form.setFieldsValue({
						...res?.data,
						contractTime: [
							moment(res?.data?.startTime),
							moment(res?.data?.finishTime),
						],
					})
					getListDetail(res?.data?.id)
					setInstanceId(res?.data?.instanceId)
					setAuditStatus(res?.data?.auditStatus)
					setOtherParams({
						...otherParams,
						requisitionName: res?.data?.requisitionName,
						requisitionOrgname: res?.data?.requisitionOrgname,
						purchaserName: res?.data?.purchaserName,
						contractTypename: res?.data?.contractTypename,
						supplierName: res?.data?.supplierName,
						supplierNo: res?.data?.supplierNo,
						startTime: res?.data?.startTime,
						finishTime: res?.data?.finishTime,
						applicantId: res?.data?.applicantId,
						payCityname: res?.data?.payCityname,
						payDeptname: res?.data?.payDeptname,
					})
					if (res?.data?.attachmentList.length) {
						getFileList(res?.data?.attachmentList)
					}
					setContractId(() => res?.data?.contractId)
					setSourceDocNo(() => res?.data?.planNo)
				}
			})
		}

		useEffect(() => {
			if (newApplyTime) {
				if (
					auditStatus &&
					auditStatus === '4' &&
					window.location.href.includes('edit') &&
					processOpen === 1
				) {
					form.setFieldsValue({
						applyTime: moment(
							moment().format('YYYY-MM-DD HH:mm:ss'),
						),
					})
				} else {
					form.setFieldsValue({
						applyTime: moment(newApplyTime),
					})
				}
			}
		}, [auditStatus, processOpen, newApplyTime])

		// 初始化-复制数据
		const getCopyPlan = (id: any) => {
			copyPlan(id).then((res: any) => {
				if (res?.success) {
					form.setFieldsValue({
						...res?.data,
						contractTime: [
							moment(res?.data?.startTime),
							moment(res?.data?.finishTime),
						],
						applicantName: props?.user?.userName,
						applyTime: moment(
							moment().format('YYYY-MM-DD HH:mm:ss'),
						),
					})
					getListDetail(id)
					setInstanceId(res?.data?.instanceId)
					setAuditStatus(res?.data?.auditStatus)
					setOtherParams({
						...otherParams,
						requisitionName: res?.data?.requisitionName,
						requisitionOrgname: res?.data?.requisitionOrgname,
						purchaserName: res?.data?.purchaserName,
						contractTypename: res?.data?.contractTypename,
						supplierName: res?.data?.supplierName,
						supplierNo: res?.data?.supplierNo,
						startTime: res?.data?.startTime,
						finishTime: res?.data?.finishTime,
						payCityname: res?.data?.payCityname,
						payDeptname: res?.data?.payDeptname,
						applicantId: props?.user?.userId,
					})
					if (res?.data?.attachmentList?.length) {
						getFileList(res?.data?.attachmentList)
					}
					setContractId(() => res?.data?.contractId)
					setSourceDocNo(() => res?.data?.planNo)
					onCodeFun()
				}
			})
		}

		useEffect(() => {
			getIsProcessOpenFun()
			getDict(
				{
					dictKeys: [
						'Car_Type',
						'Service_Type',
						'Physical_Type',
						'IN_WAREHOUSE_STATUS',
						'purchase_planitem_unit',
					],
				},
				(res: any) => {
					setDict(res)
				},
			)
			const {id} = props.location.query
			const hrefs = window.location.href
			if (id) {
				setPlanId(() => id)
			}
			if (hrefs?.includes('view')) {
				setType('view')
				getView(id)
			} else if (hrefs?.includes('add')) {
				setType('add')
				onCodeFun()
				form.setFieldsValue({
					applicantName: props?.user?.userName,
					applyTime: moment(moment().format('YYYY-MM-DD HH:mm:ss')),
				})
				setOtherParams({
					...otherParams,
					applicantId: props?.user?.userId,
				})
			} else if (hrefs?.includes('edit')) {
				setType(() => 'edit')
				getView(id)
			} else if (hrefs?.includes('copy')) {
				setType('copy')
				getCopyPlan(id)
			} else {
				setType('process')
				getView(id)
			}
		}, [])

		const customizeHeader = (value: string) => (
			<div>
				<div className={styles.tip} />
				{value}
			</div>
		)
		const submit = async (btnType: string) => {
			const {id} = props.location.query
			const itemList = JSON.parse(JSON.stringify(planitemList))
			const formData = await form.validateFields()
			const attachmentList = formData?.attachmentList?.fileList?.map(
				(item: any) => Number(item?.response?.data?.id),
			)
			const applyTime = moment(formData.applyTime).format(
				'YYYY-MM-DD HH:mm:ss',
			)
			if (!itemList?.length) {
				message.error('至少添加一条采购明细！')
				return false
			}
			const totalAmount = itemList
				?.map((item: any) => Number(item.totalAmount))
				?.reduce((prev: any, curr: any) => Number(prev) + Number(curr))
			const init = parseInt(totalAmount.toString(), 10)
			if (init.toString()?.length > 8) {
				message.error(
					'采购明细数据过大，请重新添加，总计整数部分不能超过8位数！',
				)
				return false
			}
			const list = itemList?.map((item: any) => {
				const newItem = item
				if (!newItem?.updateUser || type === 'copy') {
					delete newItem.id
				}
				return newItem
			})
			let request
			if (btnType === 'submit') {
				if (auditStatus === '9' || !id || type === 'copy') {
					const queryData = {
						...formData,
						...otherParams,
						planitemList: list,
						applyTime,
						attachmentList: attachmentList || [],
					}
					if (id && type !== 'copy') {
						queryData.id = id
					}
					if (processOpen === 1) {
						// 流程自动发起
						request = planProcessAdd(queryData)
					} else {
						// 流程未开启默认新增
						request = addPlan(queryData)
					}
				} else if (processOpen === 1 && auditStatus === '4') {
					// 流程重新发起
					request = planRelaunchFlow(id, {
						...formData,
						...otherParams,
						applyTime,
						planitemList: list,
						attachmentList: attachmentList || [],
					})
				} else {
					request = editPlan(id, {
						...formData,
						...otherParams,
						applyTime,
						planitemList: list,
						attachmentList: attachmentList || [],
					})
				}
			}
			if (btnType === 'save') {
				const queryData = {
					...formData,
					...otherParams,
					planitemList: list,
					applyTime,
					attachmentList: attachmentList || [],
				}
				if (id && type !== 'copy') {
					queryData.id = id
				}
				request = planSaveTemporary(queryData)
			}
			request
				?.then((res) => {
					if (res?.success) {
						message.success(res.msg)
						goback()
					}
				})
				.catch((err) => {
					message.error(err)
				})
			return true
		}

		// 采购类目变化
		const onRequisitionTypeChange = (value: string, option: any) => {
			setOtherParams({...otherParams, requisitionName: option?.dictValue})
		}

		// 公司变化
		const onCompanyListChange = (value: string, option: any) => {
			setOtherParams({...otherParams, payCityname: option[0]})
		}

		// 费用承担部门变化
		const onPurchaserChange = (value: string, option: any) => {
			setOtherParams({...otherParams, payDeptname: option[0]})
		}

		// 采购合同变化
		const onContractIdChange = (value: string, option: any) => {
			form.setFieldsValue({
				supplierName: option.supplierName,
				requisitionType: option.requisitionType,
			})
		}
		// 计算精度
		const multiply = (num1: any, num2: any) => {
			let total: any = num1 * num2
			if (
				JSON.stringify(num1).indexOf('.') !== -1 ||
				JSON.stringify(num2).indexOf('.') !== -1
			) {
				// num1或者num2为浮点数
				// 已小数点为分界线拆分成数组。
				const floatNum1 = JSON.stringify(num1).split('.')
				const floatNum2 = JSON.stringify(num2).split('.')
				// 获取小数点的位数，如果没有小数点则改为0
				const floatNum3 =
					floatNum1.length === 2 ? floatNum1[1].length : 0
				const floatNum4 =
					floatNum2.length === 2 ? floatNum2[1].length : 0
				// 将小数点位数相加
				const index = floatNum3 + floatNum4
				// 取近似值Math.round
				total = Math.round(total * 10 ** index) / 10 ** index
			}
			return total
		}
		// 可编辑表格
		const proColumns: ProColumns<DataSourceType>[] = [
			{
				title: (
					<>
						<span className="required">* </span> 物料编码
					</>
				),
				dataIndex: 'materialNo',
				formItemProps: {
					rules: [
						{
							required: true,
							message: '请输入物料编码',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 物料名称
					</>
				),
				dataIndex: 'materialName',
				formItemProps: {
					rules: [
						{
							required: true,
							message: '请输入物料名称',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 单位
					</>
				),
				dataIndex: 'unitType',
				valueType: 'select',
				valueEnum: getEditTableSelect(dict?.purchase_planitem_unit),
				width: 200,
				formItemProps: {
					rules: [
						{
							required: true,
							message: '请选择单位',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 数量
					</>
				),
				dataIndex: 'quantity',
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: twoDecimalPattern,
							message: '数量不正确',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 单价
					</>
				),
				dataIndex: 'price',
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: twoDecimalPattern,
							max: 10,
							message: '单价不正确',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 小计
					</>
				),
				editable: false,
				dataIndex: 'totalAmount',
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: twoDecimalPattern,
							message: '小计不正确',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 备注
					</>
				),
				dataIndex: 'remark',
				formItemProps: {
					rules: [
						{
							required: true,
							message: '请输入备注',
						},
					],
				},
			},

			{
				title: '操作',
				valueType: 'option',
				hideInTable: type === 'view' || type === 'process',
				width: 200,
				render: (text, record: any, _, action) => [
					<Button
						type="link"
						key="editable"
						onClick={() => {
							action?.startEditable?.(record.id)
						}}>
						编辑
					</Button>,
					<Popconfirm
						placement="topLeft"
						title="你确定要删除这条数据吗？"
						onConfirm={() => {
							setPlanitemList(
								planitemList.filter(
									(item: any) => item.id !== record.id,
								),
							)
						}}
						okText="确定"
						cancelText="取消">
						<Button type="link" key="delete">
							删除
						</Button>
					</Popconfirm>,
				],
			},
		]
		const purchaseColumns: ColumnsType<planAPI.columns> = [
			{
				title: '序号',
				dataIndex: 'order',
				align: 'center',
				width: 70,
				render(text, record, index) {
					return (
						<span>
							{(purchaseParams.current - 1) * 10 + index + 1}
						</span>
					)
				},
			},
			{
				title: '入库单号',
				dataIndex: 'inWarehouseNo',
				align: 'center',
				width: 200,
				render: (text: any, record: any) => (
					<>
						{text ? (
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname: '/storage/warehousing/view',
										query: {
											id: record?.id,
											type:
												record?.goodsType === '1'
													? 'vehicle'
													: 'material',
										},
									})
								}}>
								{text}
							</Button>
						) : (
							'--'
						)}
					</>
				),
			},
			{
				title: '订单号',
				dataIndex: 'auditStatus',
				align: 'center',
				width: 140,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '物料名称',
				dataIndex: 'goodsName',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '数量',
				dataIndex: 'goodsQuantity',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '入库仓库',
				dataIndex: 'inWarehouseName',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '入库时间',
				dataIndex: 'inWarehouseTime',
				align: 'center',
				width: 150,
				render: (text: string) => (
					<span>{text === '1970-01-01 00:00:00' ? '--' : text}</span>
				),
			},
			{
				title: '订单状态',
				dataIndex: 'inWarehouseStatus',
				align: 'center',
				width: 150,
				render: (text: any, record: any) => (
					<>
						{text
							? dict.IN_WAREHOUSE_STATUS?.map(
									(tag: {
										dictKey: string
										dictValue: string
									}) => {
										if (
											Number(tag.dictKey) === Number(text)
										) {
											return (
												<Tag
													color="processing"
													key={record?.id}>
													{tag.dictValue}
												</Tag>
											)
										}
										return ''
									},
							  )
							: '--'}
					</>
				),
			},
			{
				title: '操作人',
				dataIndex: 'inWarehouseMan',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '备注',
				dataIndex: 'remark',
				align: 'center',
				width: 150,
				render: (text: string) => (
					<div className="ellipsis" style={{width: 140}} title={text}>
						{text || '--'}
					</div>
				),
			},
		]
		const writeColumns: ColumnsType<planAPI.columns> = [
			{
				title: '序号',
				dataIndex: 'order',
				align: 'center',
				width: 70,
				render(text, record, index) {
					return (
						<span>
							{(purchaseParams.current - 1) * 10 + index + 1}
						</span>
					)
				},
			},
			{
				title: '发票编号',
				dataIndex: 'invoiceNo',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '付款单号',
				dataIndex: 'applypayNo',
				align: 'center',
				width: 240,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '发票日期',
				dataIndex: 'invoiceTime',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '货物名称',
				dataIndex: 'goodsName',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '货物数量',
				dataIndex: 'quantity',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '发票金额',
				dataIndex: 'amount',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
		]
		// 获取动态表格数据
		const getPlanitemList = (list: any) => {
			const data = list?.map((item: any) => {
				const newItem = item
				newItem.unitName = '个'
				const totalPrice = multiply(newItem.quantity, newItem.price)
				newItem.totalAmount = totalPrice.toFixed(2)
				return newItem
			})
			setPlanitemList(() => data)
		}

		// 计算合计
		useEffect(() => {
			if (planitemList?.length > 0) {
				const totalNums = planitemList
					?.map((item: any) => Number(item?.totalAmount))
					.reduce((prev: any, curr: any) => prev + curr)
					?.toFixed(2)
				setTotalNum(() => totalNums)
			} else {
				setTotalNum(() => '0')
			}
		}, [planitemList])

		/** 审核 */
		const onCompleteTask = async (pass: string) => {
			const examineData = await examineRef.current.getData()
			if (examineData?.url) {
				const flowParams = {
					message: examineData?.message,
					businessId: query?.id,
					instanceId,
					pass,
					attachmentList: examineData?.url?.split(','),
				}
				if (pass === '3') {
					flowParams.message = JSON.stringify(examineData)
				}
				planAuditFlow(flowParams)
					.then((res: {msg: string; success: boolean}) => {
						if (res?.success) {
							message.success(res.msg)
							if (pass === '3') {
								processRecordSave({
									bizType: 4,
									bizNo: query?.id,
									processId: instanceId,
								})
							}
							goback()
						}
					})
					.catch((err: any) => {
						message.error(err)
					})
			} else {
				message.warning('请上传附件')
			}
		}
		return (
			<div className={styles.admittanceAdd}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					{instanceId && (type === 'view' || type === 'process') ? (
						<Examine
							ref={examineRef}
							examineType={type === 'process'}
							orgId={props?.user?.orgId}
							processInstanceId={instanceId}
							required
							bizType={4}
							bizNo={query?.id}
						/>
					) : (
						''
					)}

					<Collapse
						defaultActiveKey={['1', '2']}
						ghost
						expandIconPosition="end">
						<Panel header={customizeHeader('基础信息')} key="1">
							<Form
								form={form}
								name="basic"
								layout="horizontal"
								labelCol={{flex: '160px'}}
								labelAlign="right"
								labelWrap
								initialValues={{remember: true}}
								autoComplete="off"
								disabled={
									type === 'view' || type === 'process'
								}>
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购计划申请单编号"
											name="planNo"
											rules={[{required: true}]}>
											<Input
												placeholder="请输入"
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购合同编号"
											name="contractId"
											rules={[{required: true}]}>
											<Select
												showSearch
												optionFilterProp="contractNo"
												placeholder="请选择"
												options={allContractList}
												fieldNames={{
													label: 'contractNo',
													value: 'id',
												}}
												onChange={onContractIdChange}
												disabled={
													type === 'view' ||
													type === 'process'
												}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="供应商"
											name="supplierName"
											rules={[{required: true}]}>
											<Input
												placeholder="自动带出"
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购类目"
											name="requisitionType"
											rules={[{required: true}]}>
											<TreeSelect
												showSearch
												treeNodeFilterProp="dictValue"
												placeholder="自动带出"
												style={{width: '100%'}}
												fieldNames={{
													value: 'key',
													children: 'childList',
													label: 'value',
												}}
												treeData={[
													...requisitionTypeList,
												]}
												onChange={
													onRequisitionTypeChange
												}
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="费用承担公司"
											name="payCityid"
											rules={[{required: true}]}>
											<TreeSelect
												showSearch
												treeNodeFilterProp="name"
												style={{width: '100%'}}
												placeholder="请选择"
												fieldNames={{
													label: 'name',
													value: 'id',
												}}
												treeDefaultExpandAll
												treeData={companyList}
												onChange={onCompanyListChange}
												disabled={
													type === 'view' ||
													type === 'process'
												}
											/>
										</Form.Item>
									</Col>

									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										{type === 'view' ? (
											<Form.Item
												label="需求部门"
												name="payDeptname"
												rules={[{required: true}]}>
												<Input placeholder="请选择" />
											</Form.Item>
										) : (
											<Form.Item
												label="费用承担部门"
												name="payDeptid"
												rules={[{required: true}]}>
												<TreeSelect
													showSearch
													treeNodeFilterProp="name"
													style={{width: '100%'}}
													placeholder="请选择"
													fieldNames={{
														label: 'name',
														value: 'id',
													}}
													treeDefaultExpandAll
													treeData={orgList}
													onChange={onPurchaserChange}
													disabled={
														type === 'view' ||
														type === 'process'
													}
												/>
											</Form.Item>
										)}
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="采购计划描述"
											name="remark"
											rules={[{required: true}]}>
											<TextArea
												maxLength={100}
												placeholder="请输入（最多100个字）"
												autoSize={{
													minRows: 3,
													maxRows: 6,
												}}
												disabled={
													type === 'view' ||
													type === 'process'
												}
											/>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="收货人姓名"
											name="consignee">
											<Input
												placeholder="请输入"
												maxLength={20}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="收货人电话"
											name="consigneeTel"
											rules={[
												{
													pattern:
														/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
													message: '填写的电话有误',
												},
											]}>
											<Input placeholder="请输入" />
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="收货地址"
											name="consigneeAddress">
											<TextArea
												maxLength={100}
												placeholder="请输入（最多100个字）"
												autoSize={{
													minRows: 3,
													maxRows: 6,
												}}
											/>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="申请人"
											name="applicantName">
											<Input
												placeholder="请输入"
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="申请时间"
											name="applyTime">
											{processOpen === 1 ? (
												<DatePicker
													format="YYYY-MM-DD HH:mm:ss"
													disabled
												/>
											) : (
												<DatePicker format="YYYY-MM-DD" />
											)}
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="附件上传"
											name="attachmentList">
											<Upload
												{...uploadMoreProps(
													'plan',
													0,
													fileList,
													(
														t: string,
														flist: any,
														file: any,
													) => {
														if (t === 'sizeBig') {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id.toString() !==
																		file.id.toString(),
																)
															setFileList(
																() => list,
															)
															return false
														}
														if (t === 'error') {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id.toString() !==
																		file.id.toString(),
																)
															setFileList(
																() => list,
															)
														} else if (
															[
																'done',
																'setData',
															]?.includes(t)
														) {
															setFileList(
																() => flist,
															)
														} else if (
															t === 'remove'
														) {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id !==
																		file.id,
																)
															setFileList(
																() => list,
															)
														}
														return true
													},
												)}>
												<Button
													type="primary"
													ghost
													shape="round"
													size="small"
													disabled={
														type === 'view' ||
														type === 'process'
													}>
													请选择文件
												</Button>
											</Upload>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}}>
										<div className="uploadTip">
											附件说明：附件最大支持200M，支持格式：PDF、Word、Excel、JPG、PNG、ZIP、RAR
										</div>
									</Col>
								</Row>
							</Form>
						</Panel>
						{type === 'add' || type === 'copy' ? (
							<Panel header={customizeHeader('采购明细')} key="2">
								<Button
									type="primary"
									ghost
									size="small"
									style={{marginBottom: '12px'}}
									onClick={() => {
										actionRef.current?.addEditRecord?.({
											id: `ID${(
												Math.random() * 1000000
											).toFixed(0)}`,
										})
									}}>
									新增
								</Button>
								<EditableProTable<DataSourceType>
									bordered
									rowKey="id"
									key="1"
									actionRef={actionRef}
									editableFormRef={editorFormRef}
									maxLength={5}
									// 关闭默认的新建按钮
									recordCreatorProps={false}
									columns={proColumns}
									value={planitemList}
									onChange={(value: any) =>
										getPlanitemList(value)
									}
									editable={{
										form,
										editableKeys,
										onSave: async () => true,
										onChange: setEditableRowKeys,
										actionRender: (row, config, dom) => [
											dom.save,
											dom.cancel,
										],
									}}
								/>
								<div className="totalNum">
									合计：{totalNum}元
								</div>
							</Panel>
						) : (
							''
						)}
					</Collapse>
					{type !== 'add' && type !== 'copy' ? (
						<div className={styles.tabs}>
							<Tabs
								type="card"
								defaultActiveKey="1"
								items={[
									{
										label: '采购明细',
										key: '采购明细',
										children: (
											<>
												{type === 'view' ||
												type === 'process' ? (
													''
												) : (
													<Button
														type="primary"
														ghost
														size="small"
														style={{
															marginBottom:
																'12px',
														}}
														onClick={() => {
															actionRef.current?.addEditRecord?.(
																{
																	id: (
																		Math.random() *
																		1000000
																	).toFixed(
																		0,
																	),
																},
															)
														}}>
														新增
													</Button>
												)}
												<EditableProTable<DataSourceType>
													bordered
													rowKey="id"
													key="1"
													actionRef={actionRef}
													editableFormRef={
														editorFormRef
													}
													maxLength={5}
													// 关闭默认的新建按钮
													recordCreatorProps={false}
													columns={proColumns}
													value={planitemList}
													onChange={(value: any) =>
														getPlanitemList(value)
													}
													editable={{
														form,
														editableKeys,
														onSave: async () =>
															true,
														onChange:
															setEditableRowKeys,
														actionRender: (
															row,
															config,
															dom,
														) => [
															dom.save,
															dom.cancel,
														],
													}}
												/>
												<div className="totalNum">
													合计：{totalNum}元
												</div>
											</>
										),
									},
									{
										label: '收货确认',
										key: '收货确认',
										children: (
											<CustomTable
												total={purchaseTotal}
												pagination
												params={purchaseParams}
												columns={purchaseColumns}
												callback={(pagination: any) => {
													setPurchaseParams(
														pagination,
													)
												}}
												loading={purchaseLoading}
												dataSource={purchaseList}
											/>
										),
									},
									{
										label: '发票核销',
										key: '发票核销',
										children: (
											<CustomTable
												total={writeTotal}
												pagination
												params={writeParams}
												columns={writeColumns}
												callback={(pagination: any) => {
													setWriteParams(
														() => pagination,
													)
												}}
												loading={writeLoading}
												dataSource={writeList}
											/>
										),
									},
									{
										label: '操作记录',
										key: '操作记录',
										children: (
											<OperationRecord
												businessId={
													props.location.query?.id
												}
												businessType={34}
											/>
										),
									},
								]}
							/>
						</div>
					) : (
						''
					)}
					<div className={styles.wrap}>
						<Button onClick={goback}>取消</Button>
						{type !== 'view' && type !== 'process' ? (
							<>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => submit('save')}>
									保存
								</Button>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => submit('submit')}>
									提交
								</Button>
							</>
						) : null}
						{type === 'process' ? (
							<>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => {
										onCompleteTask('1')
									}}>
									同意
								</Button>
								<Button
									onClick={() => {
										onCompleteTask('2')
									}}>
									驳回
								</Button>
								<Button
									onClick={() => {
										onCompleteTask('3')
									}}>
									拒绝
								</Button>
							</>
						) : (
							''
						)}
					</div>
				</div>
			</div>
		)
	},
)

export default connect(({global, user}: any) => ({global, user}))(add)
